import { ApiCall } from "tsrpc";

import * as fs from 'fs';
import sharp from 'sharp';
const PATH = require('path');
import { sts } from "tencentcloud-sdk-nodejs";
import COS from 'cos-nodejs-sdk-v5';
import multer from 'multer';
import { ReqUploadImg, ResUploadImg } from "../shared/api_client/PtlUploadImg";
import sdk from '../core/index';
const upload = multer({ storage: multer.memoryStorage() });
export default async function (call: ApiCall<ReqUploadImg, ResUploadImg>) {
    try {
        // 直接从请求中获取文件数据
        const { imgBuf } = call.req;
        const filename = sdk.tool.common.uuid;
        if (!imgBuf || !filename) {
            call.error('INVALID_PARAMS');
            return;
        }
        
        // 图片压缩处理
        let compressedImageBuffer: Buffer;
        try {
            compressedImageBuffer = await sharp(Buffer.from(imgBuf))
                .resize(1024, 1024, { // 限制最大尺寸为800x800
                    fit: 'inside', // 保持宽高比
                    withoutEnlargement: true // 不放大图片
                })
                .jpeg({ 
                    quality: 80, // 设置JPEG质量
                    progressive: true // 使用渐进式JPEG
                })
                .toBuffer();
        } catch (compressError) {
            console.error("图片压缩失败:", compressError);
            // 如果压缩失败，使用原图
            compressedImageBuffer = Buffer.from(imgBuf);
        }
        
        const cos = new COS({
            SecretId: process.env.COS_SECRET_ID,
            SecretKey: process.env.COS_SECRET_KEY,
        });
        
        // 上传压缩后的图片到 COS
        const { Location } = await cos.putObject({
            Bucket: "dew-1251587647",
            Region: "ap-guangzhou",
            Key: `upload/${filename}.jpg`, // 添加.jpg扩展名
            Body: compressedImageBuffer,
            ContentType: 'image/jpeg'
        });
        call.succ({
            imgUrl: `https://${Location}`
        });
        
    } catch (error) {
        console.error("COS上传失败:", error);
        call.error("IMAGE_UPLOAD_FAILED");
    }
 
}
